const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const MiniCss = require("mini-css-extract-plugin")
const { VueLoaderPlugin } = require("vue-loader")
const {HotModuleReplacementPlugin, DefinePlugin} = require("webpack")
const TerserPlugin = require('terser-webpack-plugin');
const PurifyCSS = require('purgecss-webpack-plugin')
const glob = require('glob-all')
const HardPlugin = require("hard-source-webpack-plugin")
const NODE_ENV = process.env.NODE_ENV || "development"
const isPro = NODE_ENV === "production"
// 多环境配置
const dotenv = require('dotenv')
dotenv.config({ path: '.env', debug: process.env.DEBUG })
dotenv.config({ path: `.env.${NODE_ENV}`, debug: process.env.DEBUG })
const prefixRE = /^VUE_APP_/
const env = {}
Object.keys(process.env).forEach(key => {
  if (prefixRE.test(key) || key === 'NODE_ENV') {
    env[`process.env.${key}`] = JSON.stringify(process.env[key])
  }
})

module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name]-[chunkhash:8].js"
  },
  resolve: {
    modules: [path.resolve(__dirname, "./node_modules")],
    extensions: [".js", ".vue", "json"],
    alias: {
      "@": path.resolve("src")
    }
  },
  optimization: {
    minimizer: [
      new TerserPlugin()
    ]
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCss.loader, "css-loader", "postcss-loader"]
      },
      {
        test: /\.s[ac]ss$/,
        use: [MiniCss.loader, "css-loader", "postcss-loader","sass-loader"]
      },
      {
        include: path.resolve(__dirname, "./src/assets"),
        test: /\.(png|jpe?g|gif|webp)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 3 * 1024
          }
        },
        generator: {
          filename: "images/[name][ext]",
          publicPath: "../"
        }
      },
      {
        include: path.resolve(__dirname, "./src/assets"),
        test: /\.(woff|woff2|eot)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 3 * 1024
          }
        },
        generator: {
          filename: "fonts/[name][ext]",
          publicPath: "../"
        }
      },
      {
        include: path.resolve(__dirname, "./src"),
        test: /\.js$/,
        use: ["babel-loader?cacheDirectory=true",
          // {
          // loader: "thread-loader",
          // options: {
          //   worker: 2
          // },
        // },
      ]
      },
      {
        include: path.resolve(__dirname, "./src"),
        test: /\.vue$/,
        use: ["vue-loader"]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html'
    }),
    new MiniCss({
      filename: "css/[name]-[contenthash:8].css"
    }),
    // new HardPlugin(),
    new VueLoaderPlugin(),
    new HotModuleReplacementPlugin(),
    new DefinePlugin(env),
    // 清除⽆⽤ css
    // new PurifyCSS({
    //   paths: glob.sync([
    //   // 要做 CSS Tree Shaking 的路径⽂件
    //   path.resolve(__dirname, './src/*.html'), // 请注意，我们同样需要对 html ⽂件进⾏ tree shaking
    //   path.resolve(__dirname, './src/*.js')
    //   ])
    // })
  ],
  devtool: isPro ? "cheap-module-source-map" : "source-map",
  mode: isPro ? "production" : "development",
  devServer: {
    open: true,
    port: 8080,
    hot:true,
    proxy: {
      '/vwebapi': {
        target: `http://127.0.0.1:8092/`,
        changeOrigin: true,
        pathRewrite: {
          "^/vwebapi": ""
        }
      }
    },
  }
}